import router from "@/routers/index";
import { isType } from "@/utils/util";
import { LOGIN_URL } from "@/config/config";
// import { ElNotification } from "element-plus";
import { GlobalStore } from "@/stores";
// import { RouteRecordRaw } from "vue-router";

import { AuthStore } from "@/stores/modules/auth";
import { notFoundRouter, homeRouter, devRouter, commonRouter } from "@/routers/modules/staticRouter";

// 引入 views 文件夹下所有 vue 文件
const modules = import.meta.glob("@/views/**/*.vue");
// console.log(modules, "modules");
/**
 * 初始化动态路由和保存按钮权限
 */
export const initDynamicRouter = async (
	menu: Array<Menus.Result>,
	buttons: { [key: string]: Array<string> } = {},
	is_dev: Boolean = false /* 是否为开发者账号多一个开发管理栏目 */
) => {
	const authStore = AuthStore();
	const globalStore = GlobalStore();
	try {
		authStore.setAuthButtonList(buttons);
		authStore.setAuthMenuList([ ...commonRouter,...initRouter(menu), ...(is_dev ? devRouter : [])]); //是否为开发者多一个栏目
		authStore.flatMenuListGet.concat(homeRouter).forEach((item: any) => {
			item.children && delete item.children;
			if (item.component && isType(item.component) == "string") {
				item.component = modules["/src/views" + item.component + ".vue"];
			}
			item.meta.isFull ? router.addRoute(item) : router.addRoute("layout", item)
				
		});
		// 4.最后添加 notFoundRouter
		router.addRoute(notFoundRouter);
	} catch (error) {
		// 💢 当按钮 || 菜单请求出错时，重定向到登陆页
		globalStore.setToken("");
		router.replace(LOGIN_URL);
		return Promise.reject(error);
	}
};
const initRouter = (menu: Array<Menus.Result>): Menus.MenuOptions[] => {
	return menu.map((item: Menus.Result): Menus.MenuOptions => {
		let routeRecordRaw: Menus.MenuOptions = {
			path: item.path,
			name: item.name,
			component: item.component,
			children: item.children && item.children.length > 0 ? initRouter(item.children) : [],
			meta: {
				icon: item.icon,
				title: item.title,
				isLink: item.isLink,
				isHide: item.isHide ? true : false,
				isFull: item.isFull ? true : false,
				isAffix: item.isAffix ? true : false,
				isKeepAlive: item.isKeepAlive ? true : false
			}
		};
		if (item.redirect) routeRecordRaw.redirect = item.redirect;
		return routeRecordRaw;
	});
};
